//
// Created by wuzhe on 2022/4/22.
//

#ifndef UNIVERSEROOM_REDISASYNCUTILS_H
#define UNIVERSEROOM_REDISASYNCUTILS_H
#include <hiredis/hiredis.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <functional>
#include <deque>
#include <list>
#include "Console.h"

class RedisAsync {
public:
    int fd;
    bool connect(std::string host, int port);
    int set(std::string key, std::string value, std::function<void(std::string&)>);
    int get(std::string key, std::function<void(std::string&)>);
    int del(std::string key, std::function<void(std::string&)>);
    int find(std::string key, std::function<void(std::list<std::string>&)>);
    char recvBuf[BUFSIZ] = {0};
    char sendBuf[BUFSIZ] = {0};
    int readLeftIndex = 0;
    int readRightIndex = 0;
    static RedisAsync* getSingleton() {
        static RedisAsync redisAsync;
        return &redisAsync;
    }
    std::deque<std::function<void(std::string&)>> closureQueue;

    void initSocket(int i) const;
    void processRecv();
    void processResp(char * content, int len, int& index);

private:
    RedisAsync() {
        bool res = connect("127.0.0.1", 6379);
        if (!res) {
            errLog("redis connect err");
        }
    }
    int send(const uint8_t* sendBuf, int sendBufLen);
};


#endif //UNIVERSEROOM_REDISASYNCUTILS_H
